<%layout("/eova/layout/default.html",{'title' : object.name + '列表'}){%>
<body class="easyui-layout">
	<div id="layoutNorth" region="north" title="快速查询" split="true">
		<form id="queryForm" onsubmit="return false;">
			<div id="eova-query" class="eova-form">



				<div class="eova-form-field" title="对应档案[file_id]">
					<div class="eova-form-lbl">对应档案:</div>
					<div>
						<div class="eova-find" id="file_id" name="query_file_id" value=""
							code="ATTACHMENT" field="file_id"
							url="/widget/find?code=ATTACHMENT&field=file_id&multiple=false"
							data-options=""></div>
					</div>
				</div>


				<div class="eova-form-field" title="附件名称[attachment_name]">
					<div class="eova-form-lbl">附件名称:</div>
					<div>
						<div class="eova-text" id="attachment_name"
							name="query_attachment_name" value="" data-options=""></div>
					</div>
				</div>

			</div>
		</form>
		<script>
			var x = $("#eova-query").width();
			console.log(x);
			var max = parseInt(x / 290);
			console.log('每行最多能显示：' + max);
			if (max != 0) {
				var count = 2;
				var zs = parseInt(count / max);
				var ys = count % max;
				if (ys > 0) {
					zs++;
				}
				// 计算完整显示所需高度
				var y = 40 + 25 * zs;
				$("#eova-query").parent().parent().css("height", y + "px");
				//console.log('ys'+ ys);
				//console.log('共需：'+ zs);
				//console.log('height：'+ y);
			}

			$('div[class="eova-text"]').eovatext();
			$('div[class="eova-time"]').eovatime();
			$('div[class="eova-combo"]').eovacombo();
			$('div[class="eova-find"]').eovafind();
		</script>
	</div>
	<div data-options="region:'center'"
		data-options="fit:true,border:false">
		<div id="gridToolbar" style="display: none;">
			<table>
				<tr>
					<td>
						<table>
							<tr>
								<td><a id="btn_query_grid" href="javascript:void(0);"
									class="easyui-linkbutton"
									data-options="iconCls:'icon-zoom',plain:true"
									onclick="crud_query_ATTACHMENT()"> 快速查询 </a> <script
										type="text/javascript">
										var gridId = 'grid', formId = 'queryForm';
										var crud_query_ATTACHMENT = function() {
											$('#' + gridId).datagrid(
													'load',
													sy.serializeObject($('#'
															+ formId)));
										};

										$('#' + formId)
												.keydown(
														function(event) {
															if (event.keyCode == 13) {
																crud_query_ATTACHMENT();
															}
														});
									</script></td>
								<td><a href="javascript:void(0);" class="easyui-linkbutton"
									data-options="iconCls:'icon-pageadd',plain:true"
									onclick="crud_add_ATTACHMENT()"> 新增 </a> <script
										type="text/javascript">
										var crud_add_ATTACHMENT = function() {
											var grid = $('#grid');

											var ref = '';
											// ------------------------------级联
											var parent = $('#');
											var objectField = '';
											var field = '';
											if (parent && objectField != ''
													&& field != '') {
												// 从父组件上获取选中外键值
												var parentRow = parent
														.datagrid('getSelected');
												ref = ref
														+ "?ref="
														+ field
														+ ":"
														+ parentRow[objectField];
											}
											// ------------------------------级联

											loadDialog(grid, '新增档案附件',
													'/attachment/add/ATTACHMENT'
															+ ref);
											$('.dialog-button').css(
													"text-align", "center");
										};
									</script></td>
								<td><a href="javascript:void(0);" class="easyui-linkbutton"
									data-options="iconCls:'icon-pageedit',plain:true"
									onclick="crud_update_ATTACHMENT()"> 修改 </a> <script
										type="text/javascript">
										var crud_update_ATTACHMENT = function() {
											var grid = $('#grid');
											var parentType = '';
											var row = grid
													.datagrid('getSelected');
											var num = grid
													.datagrid('getSelections').length;
											if (num > "1") {
												$.slideMsg("请勿选择多行数据！");
												return;
											}
											if (isSelected(row)) {
												var ref = '';
												// ------------------------------级联
												var parent = $('#');
												var objectField = '';
												var field = '';
												if (parent && objectField != ''
														&& field != '') {
													// 从父组件上获取选中外键值
													var parentRow = parent
															.datagrid('getSelected');
													ref = ref
															+ "?ref="
															+ field
															+ ":"
															+ parentRow[objectField];
												}
												// ------------------------------级联

												loadDialog(grid, '修改档案附件',
														'/form/update/ATTACHMENT-'
																+ row.pk_val
																+ ref);
												$('.dialog-button').css(
														"text-align", "center");
											}
										};
									</script></td>
								<td><a href="javascript:void(0);" class="easyui-linkbutton"
									data-options="iconCls:'icon-pagedelete',plain:true"
									onclick="crud_deletes_ATTACHMENT()"> 删除 </a> <script
										type="text/javascript">
										var crud_deletes_ATTACHMENT = function() {
											var $grid = $('#grid');
											var array = $grid
													.datagrid('getSelections');
											var num = array.length; //获取要删除信息的个数
											if (num == "0") {
												$.slideMsg("请选择一条记录！");
												return;
											}
											confirmDel($grid, 'ATTACHMENT',
													array);
										};
									</script></td>
								<td><a href="javascript:void(0);" class="easyui-linkbutton"
									data-options="iconCls:'icon-page',plain:true"
									onclick="crud_detail_ATTACHMENT()"> 查看 </a> <script
										type="text/javascript">
										var crud_detail_ATTACHMENT = function() {
											var grid = $('#grid');
											var row = grid
													.datagrid('getSelected');
											var num = grid
													.datagrid('getSelections').length;
											if (num > "1") {
												$.slideMsg("请勿选择多行数据！");
												return;
											}
											if (isSelected(row)) {
												loadDialog(grid, '档案附件详情',
														'/form/detail/ATTACHMENT-'
																+ row.pk_val);
												$('.dialog-button').css(
														"text-align", "center");
											}
										};
									</script></td>
								<td><a href="javascript:void(0);" class="easyui-linkbutton"
									data-options="iconCls:'icon-arrowdown',plain:true"
									onclick="eova_release()"> 下载附件 </a> <script
										type="text/javascript">
										var eova_release = function() {
											var grid = $('#grid');
											var row = grid
													.datagrid('getSelected');
											if (isSelected(row)) {
												// 新开窗口生成脚本
												window.open('/efiles/download/'
														+ row.id);
											}
										};
									</script></td>
								<td><a href="javascript:void(0);" class="easyui-linkbutton"
									data-options="iconCls:'icon-controladdblue',plain:true"
									onclick="dev_add_button()" title="快速添加按钮(仅超级管理员可见)"></a> <script
										type="text/javascript">
										var dev_add_button = function() {
											var grid = $('#grid');
											loadDialog(grid, '快速添加按钮',
													'/button/quick/ATTACHMENT');
										};
									</script></td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
		</div>
		<table id="grid" width="auto" height="auto"></table>
		<script>
			// var $grid;
			$(function() {

				// init param
				var id = "grid";
				var masterId = "";
				var $grid = $("#" + id);
				var $masterGrid;
				if (masterId != "") {
					$masterGrid = $("#" + masterId);
				}

				var menuCode = 'ATTACHMENT';// medaobject code
				var objectCode = 'ATTACHMENT';// medaobject code
				var toolbar = 'gridToolbar';// grid ref toolbar
				var isPaging = eval('true');// is show pagination
				var url = '';// diy grid load data url
				var objectJson = '';// object is json
				var fieldsJson = '';// fiedlds is json
				var configJson = '';// config is json

				if (url == '') {
					url = '/grid/query/' + objectCode;
					if (menuCode != '') {
						url = url + '-' + menuCode;
					}
				}
				var paras = $.getUrlParas();
				// 是否含有关联查询条件
				if (paras && paras.indexOf('query_') != -1) {
					url = url + '?' + paras;
				}

				// console.log(objectCode + 'isFirstLoad' + isFirstLoad);

				var config, object, fields;

				if (configJson != '') {
					config = JSON.parse(configJson);
				}
				if (objectJson != '') {
					object = JSON.parse(objectJson);
				} else {
					$.syncGetJson('/meta/object/' + objectCode, function(json) {
						object = json;
					});
				}
				if (fieldsJson != '') {
					fields = JSON.parse(fieldsJson);
				} else {
					$.syncGetJson('/meta/fields/' + objectCode, function(json) {
						fields = json;
					});
				}
				//    console.log(object);
				//    console.log(fields);

				// 当前对象是否允许初始加载数据
				var isFirstLoad = false;
				var isFirstLoadNow = eval('true');
				// 必须当前业务和对象都允许加载数据
				if (isFirstLoadNow && object.is_first_load) {
					isFirstLoad = true;
				}

				var cols = [];
				var validators = {};
				// 批量选择框
				if (!object.is_single) {
					var attr = new Object;
					attr.field = 'ck';
					attr.checkbox = true;
					cols.push(attr);
				}
				// 字段属性
				$.each(fields,
						function(i, f) {
							if (!f.is_show) {
								// continue;
								return true;
							}

							var attr = new Object;
							attr.field = f.en;
							attr.title = f.cn;
							attr.width = f.width ? f.width : 150;

							if (f.is_order) {
								attr.sortable = true;
							}

							if (f.formatter != null) {
								attr.formatter = new Function('return '
										+ f.formatter)();
							} else {
								// 默认格式化处理
								if (f.type == '复选框') {
									attr.align = 'center';
									attr.formatter = function(value, row,
											index, field) {
										var ck = '<span class="ck0">□</span>';
										if (value) {
											ck = '<span class="ck1">☑</span>';
										}
										return ck;
									};
								}
								if (f.type == '文本框' || f.type == '编辑框'
										|| f.type == '文本域') {
									attr.formatter = function(value, row,
											index, field) {
										if (value && value.length > 10) {
											//alert($.encodeHtml(value));
											return '<span title="'
													+ $.encodeHtml(value)
													+ '">'
													+ $.encodeHtml(value)
													+ '</span>'
										}
										return value;
									}
								}
							}
							// Grid Cell Editor,对象和字段允许行内编辑自增，自增长禁止编辑
							if (object.is_celledit && f.is_edit) {
								if (object.is_auto && object.is_auto == true) {
									return;
								}
								var editor = new Object;
								editor.type = f.editor;
								// 构造参数
								editor.options = {};
								if (f.type == '下拉框') {
									editor.options = {
										url : '/widget/comboJson/' + objectCode
												+ '-' + f.en,
										valueField : 'id',
										textField : 'cn',
										multiple : f.is_multiple
									}
								} else if (f.type == '查找框') {
									editor.options = {
										url : '/widget/find?code=' + objectCode
												+ '&field=' + f.en
												+ '&multiple=' + f.is_multiple
									}
								} else if (f.type == '日期框') {
									editor.options = {
										format : 'yyyy-MM-dd'
									}
								}
								editor.options['name'] = f.en;

								attr.editor = editor;

								// validator
								var rule = '';
								if (f.is_required) {
									rule = f.cn + ':required;';
								}
								if (f.validator) {
									rule = rule + f.validator;
								}
								if (rule != '') {
									validators[f.en] = {
										rule : rule
									};
								}
							}

							cols.push(attr);
						});

				console.log(cols);

				// 默认排序
				var sortName = null, sortOrder = 'asc';
				if (object.default_order) {
					var defaultOrder = object.default_order.split(' ');
					sortName = defaultOrder[0];
					if (defaultOrder.length > 1) {
						sortOrder = defaultOrder[1];
					}
				}

				var selectIndex;
				var $myGrid = $grid.datagrid({
					fit : true,
					border : false,
					striped : true,
					align : 'right',
					autoRowHeight : true,
					collapsible : false,
					remoteSort : true,
					multiSort : false,
					rownumbers : object.is_show_num,
					showFooter : true,

					ctrlSelect : true,
					singleSelect : object.is_single,

					toolbar : toolbar ? '#' + toolbar : null,
					pagination : isPaging,
					pageSize : 15,
					pageList : [ 15, 30, 50, 100, 200, 500, 1000, 2000 ],

					idField : object.pk_name,
					sortName : sortName,
					sortOrder : sortOrder,

					url : url,
					method : 'post',
					columns : [ cols ],
					// frozenColumns: [[{field:'diy_fun',title:'操作'}]],

					onHeaderContextMenu : function(e, field) {
						e.preventDefault();
						if (!cmenu) {
							createColumnMenu();
						}
						cmenu.menu('show', {
							left : e.pageX,
							top : e.pageY
						});
					},
					onBeforeLoad : function() {
						// 阻止初始化加载数据
						if (!isFirstLoad) {
							isFirstLoad = true;
							return false;
						}
					},
					onLoadSuccess : function(data) {
						if (object.is_celledit && data.total < 1) {
							// 暂时禁用，初始化不加载空行，使用Grid 分页栏按钮添加！
							$myGrid.datagrid('insertRow', {
								index : 0,
								row : {}
							});
						}
					},
					onRowContextMenu : function(e, rowIndex, rowData) {
						e.preventDefault();
						if (!rowMenu) {
							createRowMenu();
						}
						selectIndex = rowIndex;
						rowMenu.menu('show', {
							left : e.pageX,
							top : e.pageY
						});
					}
				});

				//     $grid = $myGrid;

				// 开启编辑模式
				if (object.is_celledit) {
					$myGrid.datagrid('enableCellEditing');
				}

				var rowMenu;
				function createRowMenu() {
					rowMenu = $('<div/>').appendTo('body');
					rowMenu.menu({
						id : 'rowMenu',
						onClick : function(item) {
							console.log('click menu' + item.text);
						}
					});
					rowMenu.menu('appendItem', {
						text : '刷新',
						name : 'reload',
						iconCls : 'pagination-load',
						onclick : function() {
							$myGrid.datagrid('reload');
						}
					});
					rowMenu.menu('appendItem',
							{
								text : '导出所有数据',
								name : 'exportAll',
								iconCls : 'icon-pageexcel',
								onclick : function() {
									window.location.href = '/grid/export/'
											+ objectCode;
								}
							});
					rowMenu.menu('appendItem', {
						text : '导出本页数据',
						name : 'exportAll',
						iconCls : 'icon-pageexcel',
						onclick : function() {
							// 导出Xls
							$.gridToExcel($myGrid, objectCode);
						}
					});
					if (object.is_celledit) {
						var rowData = {};
						if ($masterGrid) {
							// 获取主表选中行
							var gridSelectRow = $masterGrid
									.datagrid('getSelected');
							if (gridSelectRow) {
								// 初始添加关键字段
								var val = gridSelectRow[config.objectField];
								rowData[config.fields[0]] = val;
								rowData[config.fields[0] + '_val'] = val;
							}
						}

						rowMenu.menu('appendItem', {
							text : '删除行',
							name : 'delete',
							iconCls : 'icon-tabledelete',
							onclick : function() {
								console.log('删除行，索引=' + selectIndex);
								$myGrid.datagrid('deleteRow', selectIndex);
							}
						});
						rowMenu.menu('appendItem', {
							text : '新增行',
							name : 'add',
							iconCls : 'icon-tableadd',
							onclick : function() {
								$myGrid.datagrid('insertRow', {
									index : 0,
									row : rowData
								});
							}
						});
						rowMenu.menu('appendItem', {
							text : '保存数据',
							name : 'save',
							iconCls : 'icon-tablesave',
							onclick : function() {

								var inserted = $myGrid.datagrid('getChanges',
										'inserted');
								var deleted = $myGrid.datagrid('getChanges',
										'deleted');
								var updated = $myGrid.datagrid('getChanges',
										'updated');

								var isOk = true;
								var errorMsg = '';
								if (inserted.length > 0) {
									var json1 = JSON.stringify(inserted);
									console.log('保存add数据' + json1);
									$.syncPost('/grid/add/' + objectCode, {
										rows : json1
									}, function(result, status) {
										if (!result.success) {
											isOk = false;
											errorMsg += result.msg + '<br>';
										}
									});
								}
								if (updated.length > 0) {
									var json3 = JSON.stringify(updated);
									console.log('保存update数据' + json3);
									$.syncPost('/grid/update/' + objectCode, {
										rows : json3
									}, function(result, status) {
										if (!result.success) {
											isOk = false;
											errorMsg += result.msg + '<br>';
										}
									});
								}
								if (deleted.length > 0) {
									var json2 = JSON.stringify(deleted);
									console.log('保存delete数据' + json2);
									$.syncPost('/grid/delete/' + objectCode, {
										rows : json2
									}, function(result, status) {
										if (!result.success) {
											isOk = false;
											errorMsg += result.msg + '<br>';
										}
									});
								}

								if (isOk) {
									$.slideMsg("保存成功！");
									// 确认改动
									$myGrid.datagrid('acceptChanges');
									console.log('标记更改');
								} else {
									$.alert($, errorMsg);
								}
							}
						});
						//            rowMenu.menu('appendItem', {
						//                text: '回滚数据',
						//                name: 'reject',
						//                iconCls: 'icon-undo',
						//                onclick: function () {
						//                    //$myGrid.datagrid('rejectChanges');
						//                    console.log('回滚数据');
						//                }
						//            });
						rowMenu.menu('appendItem', {
							text : '其它功能',
							name : 'other',
							onclick : function() {
								alert('Eova is So Easy');
							}
						});
					}
				}

				var cmenu;
				function createColumnMenu() {
					cmenu = $('<div/>').appendTo('body');
					// 初始化菜单
					cmenu.menu();
					cmenu.menu('appendItem', {
						text : '编辑元字段',
						name : 'editmeta',
						iconCls : 'icon-tableedit',
						onclick : function() {
							window.open('/meta/edit/' + objectCode);
						}
					});
					cmenu.menu('appendItem', {
						text : '编辑元对象',
						name : 'editmeta',
						iconCls : 'icon-tableedit',
						onclick : function() {
							loadDialog($myGrid, '修改元对象',
									'/form/update/eova_object_code-'
											+ object.id);
						}
					});
					// 动态加载列作为菜单项目
					cmenu.menu('appendItem', {
						text : 'other',
						name : 'other',
						iconCls : ''
					});
				}

				if (object.is_celledit) {
					// validator init
					var $form = $('#grid').parent();// get datagrid-view dom is validata zone
					$form.validator({
						debug : false,
						stopOnError : true,
						focusInvalid : false,
						showOk : false,
						timely : 0,
						msgMaker : false,
						fields : validators
					});
					$form.on("validation", $.validation);
				}
				//    var pager = $myGrid.datagrid('getPager');
				//    pager.pagination({
				//        buttons: [
				//            {
				//                iconCls: 'icon-tableadd',
				//                handler: function () {
				//                    $myGrid.datagrid('insertRow', {
				//                        index: 0,
				//                        row: {}
				//                    });
				//                }
				//            },
				//            {
				//                iconCls: 'icon-tabledelete',
				//                handler: function () {
				//                    alert('tabledelete');
				//                }
				//            },
				//            {
				//                iconCls: 'icon-tablesave',
				//                handler: function () {
				//                    alert('save');
				//                }
				//            }
				//        ]
				//    });

			});
		</script>
	</div>
	<script type="text/javascript" src="/ui/js/template.js"></script>
</body>

<%}%>
